<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
date_default_timezone_set ( 'prc' );
require_once (dirname ( __FILE__ ) . "/../../PHPExcel/PHPExcel.php");
class Order extends CI_Controller {
	public function __construct() {
		parent::__construct ();
		if (! $this->session->userdata ( 'logged_in' )) {
			redirect ( 'index_admin/login' );
			exit ();
		}
	}
	/*
	 * 返回订单列表
	 */
	public function index() {
		$state = $this->uri->segment(4);
		$del = $this->uri->segment(6);
		$name = $this->uri->segment(8);
		$name=urldecode($name);//转化为汉字
		if(!isset($state)){//没有传值时默认为-2
    		$state=-2;
    	}
		if(!isset($del)){//默认为有效订单
    		$del=0;
    	}
		if(empty($name)){
    		$name="empty";
    	}
		$data ['state']=$state;
		$data ['del']=$del;
		$this->load->library ( 'pagination' );
		// 每页显示数据条数
		$per_page = 20;//暂定为20条
		
		$config ['base_url'] = site_url ( 'order/index/state/'.$state.'/del/'. $del.'/name/'.$name);
		$this->load->model ( 'order_model' );
		$this->load->model ( 'user_model' );
		
		if($name=="empty"){//这里是为了搜索
    		$name=null;
    	}
		// 数据总数
		$config ['total_rows'] = $this->order_model->count_orders ($state,$del,$name);
		
		// $config ['total_rows']=200;
		$config ['per_page'] = $per_page;
		$config ['first_link'] = '第一页';
		$config ['last_link'] = '最后一页';
		$config ['next_link'] = '下一页';
		$config ['prev_link'] = '上一页';
		$config ['uri_segment'] = 9;
		
		$this->pagination->initialize ( $config );
		$data ['links'] = $this->pagination->create_links ();
		// 偏移量
		$offset = intval ( $this->uri->segment (9) );
		$torders = $this->order_model->find_orders_by_state_del($state,$del, $name,$per_page, $offset );
		foreach($torders as $key=>$torder){//饭店推广的情况
			if(!empty($torder['promoterid'])&&$torder['promoterid']>20000){
				$puser=$this->user_model->find_by_spread($torder['promoterid']);
				$torders[$key]['promoter']=$puser['shopname'];
			}
		}
		$data ['orders']=$torders;
		$orders = $this->order_model->find_export_orders (date ( "Y-m-d"));
		$data ['ordernum'] =count($orders);
		$todaytotal=$this->order_model->get_total_by_date(date ( "Y-m-d"));//当天营业额
		$data ['todaytotal'] =round($todaytotal['total'],2);
		$yestotal=$this->order_model->get_total_by_date(date ( "Y-m-d", strtotime ( "-1 day" ) ));//昨天营业额
		$data ['yestotal'] =round($yestotal['total'],2);
		$totals=$this->order_model->get_totals();//总营业额
		$data ['totals'] =round($totals['total'],2);
		$data ['title'] = '订单管理 - 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'order/index' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 返回添加订单页面
	 */
	public function addorder() {
		$data ['title'] = '添加订单 - 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'order/addorder' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 保存订单信息
	 */
	public function saveorder() {
		$name = $this->input->post ( 'name' );
		$content=explode('-',$name);
		$userid=$content[1];
		$note = $this->input->post ( 'note' );
		$date = $this->input->post ( 'date' );
		
		$this->load->model ( 'order_model' );
		$order_exist = false;
		do{
			$orderno = $this->build_order_no ();
			if ($this->order_model->check_orderno($orderno)){
				$order_exist = true;
			}else{
				$order = array (
						'orderno' => $orderno,
						'userid' => $userid,
						'receive_time' => $date,
						'order_time' => date ( "Y-m-d H:i:s" ),
						'note' => $note,
						'total' => 0,
						'payment_mode' => 3,
						'state' => 0
				);
				$orderid=$this->order_model->create ( $order );
				$order_exist = false;//防止出现订单重复后无法出循环
			}
		}while($order_exist);
		
		if(!empty($orderid)){
			return_json ( TRUE, '', '添加成功！' );
		}else{
			return_json ( FALSE, '', '添加失败！' );
		}
	}
	/*
	 * 返回订单详情
	 */
	public function detail() {
		$id = $this->uri->segment ( 4 );
		$this->load->model ( 'order_model' );
		$order= $this->order_model->load ( $id );
		$neworder=$this->order_model->get_firstorder_by_user_date ( $order['userid'],$order['order_time'] );
		if(!empty($neworder)&&$neworder['id']!=$id){
			$data['neworderid']=$neworder['id'];
		}else{
			$data['neworderid']=null;
		}
		$data ['order'] =$order;
		$this->load->model ( 'orderdetail_model' );
		$data ['orderdetails'] = $this->orderdetail_model->find_orderdetails ( $id );
		$this->load->model ( 'coupondetail_model' );
		if(!empty($order['couponid'])){//有优惠券的情况
			$data['coupondetail']=$this->coupondetail_model->load ( $order['couponid'] );
		}else{
			$data['coupondetail']=null;
		}
		$data ['title'] = '订单详情 - 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'order/detail' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 添加订单的商品
	 */
	public function addorderdetail() {
		$orderid = $this->input->post ( 'orderid' );
		$name = $this->input->post ( 'name' );
		$content=explode('-',$name);
		$productid=$content[1];
		$price = $this->input->post ( 'price' );
		$amount = $this->input->post ( 'amount' );
		$this->load->model ( 'order_model' );
		$order= $this->order_model->load ( $orderid );
		$total=$order['total']+$price*$amount;
		$orderdetail = array (
				'orderid' => $orderid,
				'productid' => $productid,
				'price' =>$price,
				'amount' =>$amount
		);
		$this->load->model ( 'orderdetail_model' );
		$this->orderdetail_model->create( $orderdetail );
		$neworder= array (
				'total' => $total
		);
		if($order['state']>=2&&$order['state']!=4){//已确认订单且未完成
			$this->load->model ( 'product_model' );
			$product= $this->product_model->load ( $productid );
			if(!empty($product['isstock'])){//更新库存
			
			$amount2=$product['stock']-$amount;
			if($amount2>0){//库存小于等于0记为补货中
				$newproduct= array (
					'stock' => $amount2
				);
			}else{
				$newproduct= array (
					'stock' => $amount2,
					'short' => 1
				);
			}
			$this->product_model->update($productid,$newproduct) ;
			$this->record($orderid,$productid,-$amount,$amount2,3);//库存记录
			if($amount2<=0&&$product['divide']==1){
				$this->check_divide_product($productid);
			}
			
			}
		}
		if($this->order_model->update ( $orderid, $neworder )){//因为订单总额可能不变
			return_json ( TRUE, '', '添加成功！' );
		}else{
			return_json ( FALSE, '', '订单总额没有变化！' );
		}
	}
	/*
	 * 更新订单的商品数量
	 */
	public function updateorderdetail() {
		$orderid = $this->input->post ( 'orderid' );
		$orderdetailid = $this->input->post ( 'orderdetailid' );
		$amount = $this->input->post ( 'amount' );
		$this->load->model ( 'orderdetail_model' );
		$orderdetail= $this->orderdetail_model->load ( $orderdetailid );
		$this->load->model ( 'order_model' );
		$order= $this->order_model->load ( $orderid );
		$total=$order['total']-$orderdetail['amount']*$orderdetail['price']+$amount*$orderdetail['price'];
		$neworderdetail = array (
				'amount' =>$amount
		);
		$this->orderdetail_model->update( $orderdetailid,$neworderdetail );
		$neworder= array (
				'total' => $total
		);
		if($order['state']>=2&&$order['state']!=4){//已确认订单且未完成
			$this->load->model ( 'product_model' );
			$product= $this->product_model->load ( $orderdetail['productid'] );
			if(!empty($product['isstock'])){//更新库存
			
			$amount2=$product['stock']-($amount-$orderdetail['amount']);
			if($amount2>0){//库存小于等于0记为补货中
				$newproduct= array (
					'stock' => $amount2
				);
			}else{
				$newproduct= array (
					'stock' => $amount2,
					'short' => 1
				);
			}
			$this->product_model->update($orderdetail['productid'],$newproduct) ;
			$this->record($orderid,$orderdetail['productid'],$orderdetail['amount']-$amount,$amount2,4);//库存记录
			if($amount2<=0&&$product['divide']==1){
				$this->check_divide_product($productid);
			}
			
			}
		}
		if($this->order_model->update ( $orderid, $neworder )){
			return_json ( TRUE, '', '更新成功！' );
		}else{
			return_json ( FALSE, '', '订单总额没有变化！' );
		}
	}
	/*
	 * 删除订单详情
	 */
	public function deleteorderdetail() {
		$orderid = $this->input->post ( 'orderid' );
		$orderdetailid = $this->input->post ( 'orderdetailid' );
		$this->load->model ( 'orderdetail_model' );
		$orderdetail= $this->orderdetail_model->load ( $orderdetailid );
		$this->load->model ( 'order_model' );
		$order= $this->order_model->load ( $orderid );
		$total=$order['total']-$orderdetail['amount']*$orderdetail['price'];
		if(!empty($orderdetailid)){
			$this->orderdetail_model->delete( $orderdetailid);
		}
		$neworder= array (
				'total' => $total
		);
		if($order['state']>=2&&$order['state']!=4){//已确认订单且未完成
			$this->load->model ( 'product_model' );
			$product= $this->product_model->load ( $orderdetail['productid'] );
			$newproduct= array (
				'stock' => $product['stock']+$orderdetail['amount']
			);
			$this->product_model->update($orderdetail['productid'],$newproduct) ;
			$this->record($orderid,$orderdetail['productid'],$orderdetail['amount'],$product['stock']+$orderdetail['amount'],5);//库存记录
		}
		if($this->order_model->update ( $orderid, $neworder )){
			return_json ( TRUE, '', '删除成功！' );
		}else{
			return_json ( FALSE, '', '订单总额没有变化！' );
		}
	}
	/*
	 * 推送订单详情到另一个订单中
	 */
	public function pushorderdetail() {
		$orderid = $this->input->post ( 'orderid' );
		$neworderid = $this->input->post ( 'neworderid' );
		$this->load->model ( 'order_model' );
		$this->load->model ( 'orderdetail_model' );
		$order= $this->order_model->load ( $orderid );
		$neworder= $this->order_model->load ( $neworderid );
		if($orderid==$neworderid){
			return_json ( FALSE, '', '订单号相同!不能合并!' );
		}
		if($order['userid']!=$neworder['userid']){
			return_json ( FALSE, '', '饭店不同!不能合并!' );
		}
		if($order['payment_mode']!=$neworder['payment_mode']){
			return_json ( FALSE, '', '付款方式不同!不能合并!' );
		}
		$orderdetails= $this->orderdetail_model->find_orderdetails ( $orderid );
		foreach ( $orderdetails as $orderdetail ) {
			$neworderdetail = array (
				'orderid' => $neworderid,
				'productid' => $orderdetail['productid'],
				'price' =>$orderdetail['price'],
				'amount' =>$orderdetail['amount']
			);
			$this->orderdetail_model->create( $neworderdetail );
		}
		$oldorder= array (
				'state' => -1,
				'merge' => 1,
				'del' => 1
		);
		$this->order_model->update ( $orderid, $oldorder );//将之前的订单设为已合并
		$neworder2= array (
				'total' => $order['total']+$neworder['total']    //更新总金额
		);
		if($this->order_model->update ( $neworderid, $neworder2 )){
			return_json ( TRUE, '', '推送成功！' );
		}else{
			return_json ( FALSE, '', '订单总额没有变化!' );
		}
	}
	/*
	 * 提醒用户支付
	 */
	public function remindPay(){
		$orderid= $this->input->post ( 'orderid' );
		$this->load->model ( 'order_model' );
		$order=$this->order_model->load( $orderid );
		
		$sid="9f014d8f371d9a94348092594b971d3f";
		$appid="55953fa1a9014153b89e194bee63770a";
		$key="d4435599239290ed5e40df062cc85e37";
		$time=date("YmdHis").'111';
		$sign=md5($sid.$time.$key);
		$phone=$order['cellphone'];
		$templateid="13116";
		$param=substr($order['orderno'],-5);//
		
		$url="http://www.ucpaas.com/maap/sms/code?sid=".$sid."&appId=".$appid."&time=".$time."&sign=".$sign."&to=".$phone."&templateId=".$templateid."&param=".$param;
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, $url );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_HEADER, 0 );
		$output = curl_exec ( $ch );
		curl_close ( $ch );
		$output = json_decode($output);
		if($output->resp->respCode=="000000"){//短信发送成功
			$message = array (
					'phone' => $phone,
					'state' => 1,
					'smsid' => $output->resp->templateSMS->smsId,
					'createdate' => $output->resp->templateSMS->createDate
			);
			$this->load->model ( 'message_model' );
			$this->message_model->create($message);//更新短信表
			return_json ( TRUE, "", '提醒成功！' );
		}
		return_json ( FALSE, "", '提醒失败！' );
	}
	/*
	 * 提醒下单时间
	 */
	public function remindTime(){
		$orderid= $this->input->post ( 'orderid' );
		$this->load->model ( 'order_model' );
		$order=$this->order_model->load( $orderid );
		
		$sid="9f014d8f371d9a94348092594b971d3f";
		$appid="55953fa1a9014153b89e194bee63770a";
		$key="d4435599239290ed5e40df062cc85e37";
		$time=date("YmdHis").'111';
		$sign=md5($sid.$time.$key);
		$phone=$order['cellphone'];
		$templateid="13117";
		$param=substr($order['orderno'],-5);//
		
		$url="http://www.ucpaas.com/maap/sms/code?sid=".$sid."&appId=".$appid."&time=".$time."&sign=".$sign."&to=".$phone."&templateId=".$templateid."&param=".$param;
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, $url );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_HEADER, 0 );
		$output = curl_exec ( $ch );
		curl_close ( $ch );
		$output = json_decode($output);
		if($output->resp->respCode=="000000"){//短信发送成功
			$message = array (
					'phone' => $phone,
					'state' => 1,
					'smsid' => $output->resp->templateSMS->smsId,
					'createdate' => $output->resp->templateSMS->createDate
			);
			$this->load->model ( 'message_model' );
			$this->message_model->create($message);//更新短信表
			return_json ( TRUE, "", '提醒成功！' );
		}
		return_json ( FALSE, "", '提醒失败！' );
	}
	public function supplierorderdetail() {
		$id = $this->uri->segment ( 4 );
		// $id = $this->input->post('id');
		$this->load->model ( 'order_model' );
		$data ['item'] = $this->order_model->load_supplier_order( $id );
		$this->load->model ( 'orderdetail_model' );
		$data ['orderdetails'] = $this->orderdetail_model->find_supplierorderdetails ( $id );
		$data ['title'] = '供货商订单详情 - 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'order/supplierorderdetail' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 更新收货时间
	 */
	public function updatereceive() {
		$orderid = $this->input->post ( 'orderid' );
		$receive = $this->input->post ( 'receive' );
		$order = array (
				'receive_time' => $receive
		);
		$this->load->model ( 'order_model' );
		if ($orderid) {
			if($this->order_model->update( $orderid, $order )){
				return_json ( TRUE, '', '修改成功！' );
			}else{
				return_json ( FALSE, '', '数据未变动！' );
			}
		}
	}
	/*
	 * 更新支付方式
	 */
	public function updatepayment() {
		$orderid = $this->input->post ( 'orderid' );
		$payment = $this->input->post ( 'payment' );
		$order = array (
				'payment_mode' => $payment
		);
		$this->load->model ( 'order_model' );
		if ($orderid) {
			if($this->order_model->update( $orderid, $order )){
				return_json ( TRUE, '', '修改成功！' );
			}else{
				return_json ( FALSE, '', '数据未变动！' );
			}
		}
	}
	/*
	 * 更新订单信息
	 */
	public function edit() {
		$id = $this->input->post ( 'id' );
		$payment_mode = $this->input->post ( 'payment' );
		$state=$this->input->post ( 'state' );
		$this->load->model ( 'order_model' );
		$this->load->model ( 'orderdetail_model' );
		$temporder=$this->order_model->load( $id);
		if($temporder['del']==1){
			return_json ( FALSE, '', '该订单已被删除！' );
		}
		if(!empty($payment_mode)){//完成订单时才会传付款方式
			if($payment_mode=="3"){//货到付款，完成订单时添加支付时间
				$order = array (
						'state' => $state,
						'payment_time' => date ( "Y-m-d H:i:s" ),
						'arrival_time' => date ( "Y-m-d H:i:s" )  
				);
			}else{
				$order = array (
						'state' => $state,
						'arrival_time' => date ( "Y-m-d H:i:s" )  
				);
			}
			$this->addscore($id);//增加积分
			$this->addfee($id);//增加用户推广费用
		}else{
			$order = array (
					'state' => $state
			);
			if($temporder['state']==2&&$state=="0"){//确认订单后又设为待支付状态
				$this->updatestock($id,0,10);
			}
			if($state=="2"&&$temporder['state']!=2){//确认订单时,确保不会重新确认
				$this->addactivity($temporder);
				$this->updatestock($id,1,6);
			}
		}
		if ($id) {
			if($this->order_model->update ( $id, $order )){
				return_json ( TRUE, '', '操作成功！' );
			}else{
				return_json ( FALSE, '', '操作失败！' );
			}
		}
	}
	/*
	 * 判断订单是否属于首单活动
	 */
    private function addactivity($order){
    	$this->load->model ( 'order_model' );
		$this->load->model ( 'orderdetail_model' );
  		$ordernum=$this->order_model->find_orders_num( $order['userid']);
		if(empty($order['couponid'])&&$ordernum==0){//首单优惠需要没有使用优惠券
			$this->load->model ( 'activity_model' );
			$activity=$this->activity_model->find_valid_first_activity();
			if(!empty($activity)){
				if($order['total']>=$activity['full']){
					$orderdetail=array (
						'orderid' => $order['id'],
						'productid' => $activity['productid'],
						'price' => $activity['price'],
						'amount' => $activity['amount']
			    	);
					$this->orderdetail_model->create ( $orderdetail );
				}
			}
		}	
	}
	/*
	 * 根据订单ID增加用户积分
	 */
    private function addscore($orderid){
    	$this->load->model ( 'score_model' );
    	$this->load->model ( 'order_model' );
		$temporder=$this->order_model->load($orderid);
		$this->load->model ( 'user_model' );
		$user=$this->user_model->load( $temporder['userid']);
		$score=round($temporder['total']);
		if(!empty($temporder['couponid'])){
			$this->load->model ( 'coupondetail_model' );
			$coupon=$this->coupondetail_model->load($temporder['couponid']);
			$score=$score-$coupon['off'];
		}
		if($score>0){
			$newuser=array(
				'score'=>$user['score']+$score
			);
			$this->user_model->update($user['id'],$newuser);//更新用户积分
			$record= array (
				'userid' => $temporder['userid'],
				'num'=>$score,
				'type'=>1,
				'date'=>date ( 'Y-m-d H:i:s', time () ),
				'orderno'=>$temporder['orderno'],
				'note'=>'购物积分'
			);
			$this->score_model->create ($record);//记录账户积分变动
		}
	}
	/*
	 * 增加用户推广费用
	 */
	private function addfee($orderid){
		$this->load->model ( 'order_model' );
		$temporder=$this->order_model->load($orderid);
		$this->load->model ( 'user_model' );
		$user=$this->user_model->load( $temporder['userid']);
		if($user['promoterid']>20000){
			$puser=$this->user_model->find_by_spread($user['promoterid']);
			$total=$temporder['total'];
			if(!empty($temporder['couponid'])){
				$this->load->model ( 'coupondetail_model' );
				$coupondetail = $this->coupondetail_model->load ($temporder['couponid']);
				$total=$total-$coupondetail['off'];
			}
			$total=$total*0.005;
			$newuser=array(
				'balance'=>$puser['balance']+$total
			);
			$this->user_model->update($puser['id'],$newuser);//更新用户余额
			$this->load->model ( 'balancerecord_model' );
			$record= array (
				'userid' => $puser['id'],
				'num'=>$total,
				'type'=>2,
				'date'=>date ( 'Y-m-d H:i:s', time () ),
				'note'=>'推广提成'
			);
			$this->balancerecord_model->create ($record);//记录账户余额变动
			$this->load->model ( 'fee_model' );
			$fee= array (
				'promoterid' => $puser['spread'],
				'amount'=>$total,
				'userid'=>$user['id'],
				'date'=>date ( 'Y-m-d H:i:s', time () )
			);
			$this->fee_model->create ($fee);//记录用户推广提成
		}
	}
	/*
	 * 根据订单ID更新商品库存信息(1是减少库存，0是增加库存)
	 */
    private function updatestock($id,$state,$type){
    	$this->load->model ( 'orderdetail_model' );
    	$this->load->model ( 'product_model' );
		$orderdetails=$this->orderdetail_model->find_orderdetails( $id);	
		foreach($orderdetails as $orderdetail){
			$product=$this->product_model->load( $orderdetail['productid']);	
			if(!empty($product['isstock'])){//更新库存
				if($state==1){
					$temp=$product['stock']-$orderdetail['amount'];
				}else{
					$temp=$product['stock']+$orderdetail['amount'];
				}
				if($temp>0){
					$newproduct = array (
						'stock' => $temp
					);
					$this->product_model->update($product['id'],$newproduct);
				}else{//库存小于等于0 记为补货
					$newproduct = array (
						'stock' => $temp,
						'short' => 1
					);
					$this->product_model->update($product['id'],$newproduct);
					if($product['divide']==1){//判断是否拆分
						$this->check_divide_product($product['id']);
					}
				}
				if($state==1){
					$this->record($id,$product['id'],-$orderdetail['amount'],$temp,$type);//库存记录
				}else{
					$this->record($id,$product['id'],$orderdetail['amount'],$temp,$type);
				}
			}
		}
    }
	/*
	 * 删除及恢复订单
	 */
	public function setdel() {
		$id = $this->input->post ( 'id' );
		$del = $this->input->post ( 'del' );
		$state = $this->input->post ( 'state' );
		$order = array (
				'del' => $del,
				'state' => $state
		);
		$this->load->model ( 'order_model' );
		$temporder=$this->order_model->load( $id);
		if($temporder['state']>=2&&$del==1){//只有确认订单后删除订单时才更新库存
			$this->updatestock($id,0,7);
		}
		if ($id) {
			if($this->order_model->update ( $id, $order )){
				return_json ( TRUE, '', '操作成功！' );
			}else{
				return_json ( FALSE, '', '操作失败！' );
			}
		}
	}
	public function update() {
		// 前台传入的id
		// $id = $params ['id'];
		$id = $this->input->post ( 'id' );
		$settle = $this->input->post ( 'settle' );
		$order = array (
				'settle' => $settle
		);
		$this->load->model ( 'order_model' );
		if ($id) {
			if($this->order_model->update_supplier_order ( $id, $order )){
				return_json ( TRUE, '', '操作成功！' );
			}else{
				return_json ( FALSE, '', '操作失败！' );
			}
		}
	}
	/*
	 * 跳转到分配送货员页面
	 */
	public function delivery() {
		$id = $this->uri->segment(4);
		$data['orderid']=$id;
		$this->load->model ( 'deliveryman_model' );
		$data ['deliverymans'] =$this->deliveryman_model->find_all_deliverymans ();
		$data ['title'] = '分配送货员- 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'order/delivery' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 分配送货员
	 */
	public function setdelivery() {
		$orderid = $this->input->post ( 'orderid' );
		$delivery = $this->input->post ( 'delivery' );
		$order = array (
				'deliverymanid' => $delivery
		);
		$this->load->model ( 'order_model' );
		if ($orderid) {
			if($this->order_model->update( $orderid, $order )){
				return_json ( TRUE, '', '分配成功！' );
			}else{
				return_json ( FALSE, '', '分配失败！' );
			}
		}
	}
	/*
	 * 跳转到修改备注页面
	 */
	public function note() {
		$id = $this->uri->segment(4);
		$this->load->model ( 'order_model' );
		$order= $this->order_model->load ( $id );
		$data ['order'] =$order;
		$data ['title'] = '修改备注- 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'order/note' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 保存备注信息
	 */
	public function setnote() {
		$orderid = $this->input->post ( 'orderid' );
		$note = $this->input->post ( 'note' );
		$order = array (
				'note' => $note
		);
		$this->load->model ( 'order_model' );
		if ($orderid) {
			if($this->order_model->update( $orderid, $order )){
				return_json ( TRUE, '', '修改成功！' );
			}else{
				return_json ( FALSE, '', '修改失败！' );
			}
		}
	}
	/*
	 * 跳转到添加商品备注页面(暂时不需要)
	 */
	public function addrequirement() {
		$userid = $this->uri->segment(4);
		$productid = $this->uri->segment(4);
		$data['userid']=$userid;
		$data['productid']=$productid;
		$data ['title'] = '添加商品备注- 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'order/addrequirement' );
		$this->load->view ( 'footer' );
	}
	public function supplierorderlist(){
		$ordertype = $this->uri->segment(4);
		
		if(empty($ordertype)){
    		$ordertype=1;
    	}
			
		$this->load->library ( 'pagination' );
		// 每页显示数据条数
		$per_page = 10;//暂定为10条
		
		$config ['base_url'] = site_url ( 'order/supplierorderlist/ordertype/'.$ordertype );
		$this->load->model ( 'order_model' );
		// 数据总数
		$config ['total_rows'] = $this->order_model->count_supplier_orders ();
		// $config ['total_rows']=200;
		$config ['per_page'] = $per_page;
		$config ['first_link'] = '第一页';
		$config ['last_link'] = '最后一页';
		$config ['next_link'] = '下一页';
		$config ['prev_link'] = '上一页';
		$config ['uri_segment'] = 5;
		
		$this->pagination->initialize ( $config );
		$data ['links'] = $this->pagination->create_links ();
		// 偏移量
		$offset = intval ( $this->uri->segment ( 5 ) );
		
		if($ordertype==1){
    		$type="order_time";
    		$order="desc";
    	}else if($ordertype==2){
    		$type="supplierid";
    		$order="asc";
    	}
		
		$data ['orders'] = $this->order_model->find_supplier_orders ( $per_page, $offset,$type,$order);
		$data ['title'] = '供货商订单 - 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'order/supplierorderlist' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 自动评分功能
	 */
	public function comment() {
		$order = array (
				'score' => 5
		);
		$this->load->model ( 'order_model' );
		if($this->order_model->update_scores($order)){
			return_json ( TRUE, '', '自动评分成功！' );
		}else{
			return_json ( FAlSE, '', '自动评分失败！' );
		}
	}
	/*
	 *一键操作功能
	 */
	public function oneclick() {
		$state = $this->input->post ( 'state' );
		$this->load->model ( 'order_model' );
		if($state==2){//确认订单时修改库存
			$orders=$this->order_model->find_uncheck_orders();
			foreach($orders as $order){
				$this->addactivity($order);
				$this->updatestock($order['id'],1,8);
			}
		}
		if($state==4){
			$orders=$this->order_model->find_unfinish_orders();
			foreach($orders as $order){
				$this->addscore($order['id']);//增加用户积分
				$this->addfee($order['id']);//增加用户推广费用
			}
		}
		if($this->order_model->update_orders($state)){
			return_json ( TRUE, '', '操作成功！' );
		}else{
			return_json ( FAlSE, '', '数据未改变！' );
		}
	}
	/*
	 * 删除优惠券
	 */
	public function deletecoupon() {
		$orderid = $this->input->post ( 'orderid' );
		$order = array (
				'couponid' => 0
		);
		$this->load->model ( 'order_model' );
		if ($orderid) {
			if($this->order_model->update( $orderid, $order )){
				return_json ( TRUE, '', '删除成功！' );
			}else{
				return_json ( FALSE, '', '删除失败！' );
			}
		}
	}
	 /*
	 *录入进货价(暂时不需要)
	 */ 
	public function importPrices(){
		$date = $this->uri->segment(4);
		$payment="0";
		$this->load->model ( 'orderdetail_model' );
		$this->load->model ( 'purprice_model' );
		$products = $this->orderdetail_model->find_export_report ($date,$payment);
		$adminid = $this->session->userdata ( 'id' );
		foreach($products as $product){
			$purprice=$this->purprice_model->find_by_date_product ($date,$product['id']);
			if(empty($purprice)){
				$newpurprice = array (
					'productid' => $product['id'],
					'purprice' => $product['purprice'],
					'adminid' => $adminid,
					'add_time' => date ( "Y-m-d")
				);
				$this->purprice_model->create ($newpurprice);
			}
		}
		$purprices=$this->purprice_model->find_by_date ($date);
		$data ['purprices']=$purprices;
		$data ['title'] = '录入进货价 - 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'order/purprice' );
		$this->load->view ( 'footer' );
    }  
	/*
	 * 根据日期得到要采购的订单(导出订单)
	 */
	public function exportOrders() {
		$date = $this->uri->segment(4);
		$date=date ( "Y-m-d", strtotime($date));
		$resultPHPExcel = new PHPExcel ();
		$this->load->model ( 'region_model' );
		$this->load->model ( 'orderdetail_model' );
		$this->load->model ( 'requirement_model' );
		$this->load->model ( 'order_model' );
		$orders = $this->order_model->find_export_orders ($date);
	
		$activeindex=0;//当前表格序号
		$cash=1;//货到付款编号
		foreach ( $orders as $order ) {
			if($activeindex>0){
				$resultPHPExcel->createSheet();
				$resultPHPExcel->setactivesheetindex($activeindex);
			}
			$objActSheet = $resultPHPExcel->getActiveSheet();
			//设置当前活动sheet的名称
			$objActSheet->setTitle('订单'.$order['id']);
			
			//$objActSheet->getColumnDimension("A")->setWidth(21.5);
			$objActSheet->getRowDimension(1)->setRowHeight(58);
			
			/*实例化插入图片类*/
			$objDrawing = new PHPExcel_Worksheet_Drawing();
			/*设置图片路径 切记：只能是本地图片*/
			$objDrawing->setPath("./img/logo.png");
			/*设置图片高度*/
			$objDrawing->setHeight(65);
			/*设置图片要插入的单元格*/
			$objDrawing->setCoordinates("A1");
			//$objActSheet->mergeCells('A1:D6');
			/*设置图片所在单元格的格式*/
			$objDrawing->setOffsetX(4);//X轴偏移量
			$objDrawing->setOffsetY(4);
			$objDrawing->setRotation(10);
			$objDrawing->getShadow()->setVisible(true);
			$objDrawing->getShadow()->setDirection(50);
			$objDrawing->setWorksheet($objActSheet);
			
			$objActSheet->setCellValue ( 'C1', '送货单');
			//$objActSheet->getStyle('E1')->getFont()->setName('宋体');
			$objActSheet->getStyle('C1')->getFont()->setBold(true);
			$objActSheet->getStyle('C1')->getFont()->setSize(28);
			$objActSheet->getStyle('C1')->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
			//$objActSheet->getStyle('C1')->getAlignment ()->setHorizontal (PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);
			
			$objActSheet->setCellValue ( 'A2', '订单号：'.$order ['orderno']  );
			if($order['payment_mode']==1){
				$mode='支付宝支付(已付清)';
			}
			if($order['payment_mode']==2){
				$mode='微信支付(已付清)';
			}
			if($order['payment_mode']==3){
				$mode='货到付款('.$cash.')';
				$cash++;
			}
			if($order['payment_mode']==4){
				$mode='余额支付(已付清)';
			}
			$objActSheet->setCellValue ( 'A3', '支付方式：'.$mode);
			$objActSheet->getStyle('A3')->getFont()->setBold(true);
			$objActSheet->getStyle('A3')->getFont()->setSize(12);
			if(!empty($order ['late_time'])){
				$objActSheet->setCellValue ( 'A4', '时间:'.date ( "Y-m-d",strtotime($order ['receive_time'] )).'【'.$order ['early_time'].'-'.$order ['late_time'].'】');
			}else{
				$objActSheet->setCellValue ( 'A4', '时间:'.date ( "Y-m-d",strtotime($order ['receive_time'] )));
			}
			if(!empty($order['district'])){
				$region = $this->region_model->load ($order['district']);//得到区的名称
				$objActSheet->setCellValue ( 'A5', '地址：'.$region['name'].' '.$order ['address']);
			}else{
				$objActSheet->setCellValue ( 'A5', '地址：'.$order ['address']);
			}
			$objActSheet->mergeCells('A6:G6');
			
			if(!empty($order ['note'])){
			$length=124;
			$width=ceil(strlen($order ['note'])/$length);
			//$objActSheet ->getStyle('A6')->getAlignment()->setShrinkToFit(true);//字体变小以适应宽
			$objActSheet ->getStyle('A6')->getAlignment()->setWrapText(true);//自动换行 
			$objActSheet->getRowDimension(6)->setRowHeight(15*$width);
			//$objActSheet->getRowDimension(6)->setAutoSize(true);  
			$objActSheet->setCellValue ( 'A6', '备注：'.$order ['note']);
			}else{
				$objActSheet->setCellValue ( 'A6', '备注：无');
			}
			$objActSheet->mergeCells('D1:E2');
			$objActSheet->mergeCells('F1:G2');
			
			$objDrawing = new PHPExcel_Worksheet_Drawing();
			//$objDrawing->setResizeProportional(false);
			/*设置图片路径 切记：只能是本地图片*/
			$objDrawing->setPath("./img/weixin.png");
			/*设置图片高度*/
			$objDrawing->setHeight(100);
			//$objDrawing->setWidth(200);
			/*设置图片要插入的单元格*/
			$objDrawing->setCoordinates('F1');
			//$objActSheet->mergeCells('A1:D6');
			/*设置图片所在单元格的格式*/
			$objDrawing->setOffsetX(25);
			$objDrawing->setOffsetY(10);
			$objDrawing->setRotation(20);
			$objDrawing->getShadow()->setVisible(true);
			$objDrawing->getShadow()->setDirection(50);
			$objDrawing->setWorksheet($objActSheet);
			
			$objActSheet->mergeCells('F5:G5');
			$objActSheet->setCellValue ( 'F5', '微信扫一扫');
			$objActSheet->getStyle('F5')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			
			$objActSheet->setCellValue ( 'C2', '客户：'.$order ['shopname'] );
			$objActSheet->setCellValue ( 'C3','联系人：'.$order ['name']  );
			$objActSheet->setCellValue ( 'C4','联系电话：'.$order ['cellphone']);
			//$objActSheet->setCellValue ( 'A7', '采购日期' );
			//$objActSheet->setCellValue ( 'B7', date ( "Y-m-d", strtotime ( "+1 day" ) ) );
			$objActSheet->setCellValue ( 'A8', '序号' );
			$objActSheet->setCellValue ( 'B8', '商品名称' );
			$objActSheet->mergeCells('B8:C8');
			$objActSheet->setCellValue ( 'D8', '单位' );
			$objActSheet->setCellValue ( 'E8', '数量' );
			$objActSheet->setCellValue ( 'F8', '单价' );
			$objActSheet->setCellValue ( 'G8', '金额' );
			$objActSheet->getRowDimension(8)->setRowHeight(18);
			
			$orderdetails = $this->orderdetail_model->find_orderdetails ( $order ['id'] );
			$j=1;
			foreach ( $orderdetails as $orderdetail ) {
				
				$objActSheet->setCellValue ( 'A' . ($j + 8),$j);
				$objActSheet->mergeCells('B'.  ($j + 8).':C'.($j + 8));//合并BC两列
				$name=$orderdetail ['name'];
				if (! empty($orderdetail ['description'])) {
					$name=$name. '-' . $orderdetail ['description'];
				}
				$requirement = $this->requirement_model->find_by_user_and_product ($order['userid'],$orderdetail['productid']);
				if(!empty($requirement)){
					$name=$name. '-*' . $requirement ['content'];
				}
				$length=61;
				$width=ceil(strlen($name)/$length);
				$objActSheet ->getStyle('B'. ($j + 8))->getAlignment()->setWrapText(true);//自动换行 
				$objActSheet->getRowDimension($j + 8)->setRowHeight(18*$width);
				$objActSheet->setCellValue ( 'B' . ($j + 8), $name);		
				//$objActSheet->setCellValue ( 'B' . ($j + 8), $orderdetail ['name'] );
				$objActSheet->setCellValue ( 'D' . ($j + 8), $orderdetail ['unit'] );
				$objActSheet->setCellValue ( 'E' . ($j + 8), $orderdetail ['amount'] );
				$objActSheet->setCellValue ( 'F' . ($j + 8), $orderdetail ['price'] );
				$sum=$orderdetail ['amount']*$orderdetail ['price'];//待确定，是否需要调整
				$objActSheet->setCellValue ( 'G' . ($j + 8), $sum );
				//$objActSheet->getRowDimension($j+8)->setRowHeight(18);
				$j ++;
			}
				if(empty($order['couponid'])){
					$objActSheet->getRowDimension($j+8)->setRowHeight(18);
					$objActSheet->mergeCells('A'.($j + 8).':G'.($j + 8));
					$objActSheet->setCellValue ( 'A'.($j + 8), '总计：￥'.$order['total'] );
				}else{
					$this->load->model ( 'coupondetail_model' );
					$coupondetail = $this->coupondetail_model->load ($order['couponid']);
					$objActSheet->getRowDimension($j+8)->setRowHeight(36);
					$objActSheet->mergeCells('A'.($j + 8).':G'.($j + 8));
					$objActSheet->getStyle('A'.($j + 8))->getAlignment()->setWrapText(true);//自动换行
					$objActSheet->setCellValue ( 'A'.($j + 8), "优惠券：-".$coupondetail['off']."\n总计：￥".($order['total']-$coupondetail['off']));
				}
			$objActSheet->getStyle('A'.($j + 8))->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT);//合计右对齐
			$styleArray = array(//加入边框
					'borders' => array(
							'allborders' => array(
									'style' => PHPExcel_Style_Border::BORDER_THIN
							),
					),
			);
			$objActSheet->getStyle('A8:G'.($j + 8))->applyFromArray($styleArray);
			//左对齐
			$objActSheet->getStyle ( 'A8:A' .($j+7) )->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_CENTER );
			$objActSheet->getStyle ( 'D8:D' .($j+7) )->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_CENTER );
			$objActSheet->getStyle ( 'E8:G' .($j+7) )->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_RIGHT );
			$objActSheet->getStyle ( 'B8:C' .($j+7) )->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_LEFT );
			
			$objActSheet->getStyle ( 'A8:G' .($j+8) )->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);//垂直居中
				
			$objActSheet->setCellValue ( 'B'.($j + 9), '送货人：'.$order ['dname']);
			$objActSheet->setCellValue ( 'F'.($j + 9), '收货人签字：');
			
			$objActSheet->mergeCells('A'.($j + 11).':G'.($j + 11));
			$objActSheet->getStyle('A'.($j + 11))->getAlignment()->setWrapText(true);//自动换行
			if(!empty($order ['service'])){
				$objActSheet->setCellValue ( 'A'.($j + 11), "*星号后面内容为该商品的客户备注内容\n感谢您选择集市宝！\n温馨提示：生鲜类货品（蔬菜水果、鲜肉禽蛋、海鲜水产、冷藏或冻货、面点等）当场验收，签收后将不享受退换货服务；非生鲜类货品（米面粮油，调料干货，厨房用品等）在您签收货品24小时后将不再享受退换货服务；售后热线".$order ['service']."。");
			}else{
			if(!empty($order ['phone'])){
				$objActSheet->setCellValue ( 'A'.($j + 11), "*星号后面内容为该商品的客户备注内容\n感谢您选择集市宝！\n温馨提示：生鲜类货品（蔬菜水果、鲜肉禽蛋、海鲜水产、冷藏或冻货、面点等）当场验收，签收后将不享受退换货服务；非生鲜类货品（米面粮油，调料干货，厨房用品等）在您签收货品24小时后将不再享受退换货服务；售后热线".$order ['phone']."。");
			}else{
				$objActSheet->setCellValue ( 'A'.($j + 11), "*星号后面内容为该商品的客户备注内容\n感谢您选择集市宝！\n温馨提示：生鲜类货品（蔬菜水果、鲜肉禽蛋、海鲜水产、冷藏或冻货、面点等）当场验收，签收后将不享受退换货服务；非生鲜类货品（米面粮油，调料干货，厨房用品等）在您签收货品24小时后将不再享受退换货服务；售后热线18757115951。");
			}
			}
			$objActSheet->getRowDimension($j + 11)->setRowHeight(75);
			
			$objActSheet->getColumnDimension ( 'A' )->setWidth ( 5 );
			$objActSheet->getColumnDimension ( 'B' )->setWidth ( 25);
			$objActSheet->getColumnDimension ( 'C' )->setWidth ( 20 );
			$objActSheet->getColumnDimension ( 'D' )->setWidth ( 10 );
			$objActSheet->getColumnDimension ( 'E' )->setWidth ( 10 );
			$objActSheet->getColumnDimension ( 'F' )->setWidth ( 10 );
			$objActSheet->getColumnDimension ( 'G' )->setWidth ( 10 );
			
			$objActSheet->getHeaderFooter()->setOddFooter('&B&C第&P页,共&N页');
			
			$activeindex++;
		}
		$outputFileName = '订单表.xls';
		$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
		// ob_start(); ob_flush();
		header ( "Content-Type: application/force-download" );
		header ( "Content-Type: application/octet-stream" );
		header ( "Content-Type: application/download" );
		header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
		header ( "Content-Transfer-Encoding: binary" );
		header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
		header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
		header ( "Pragma: no-cache" );
		$xlsWriter->save ( "php://output" );
	}
	/*
	 * 根据日期得到要采购的商品列表(导出采购单)
	 */
	public function exportOrderdetails() {
		$date = $this->uri->segment(4);
		$resultPHPExcel = new PHPExcel ();
		$objActSheet = $resultPHPExcel->getActiveSheet();
		$objActSheet->setCellValue ( 'A1', '采购日期：'.date ( "Y-m-d", strtotime ( "$date +1 day" )));
		$objActSheet->setCellValue ( 'A2', '商品名称' );
		$objActSheet->mergeCells('A2:C2');
		$objActSheet->setCellValue ( 'D2', '数量' );
		$objActSheet->setCellValue ( 'E2', '单位' );
		$objActSheet->setCellValue ( 'F2', '简单描述' );
		$objActSheet->setCellValue ( 'G2', '库存' );
		$this->load->model ( 'order_model' );
		$this->load->model ( 'orderdetail_model' );
		$this->load->model ( 'cost_model' );
		$this->load->model ( 'lost_model' );
		$this->load->model ( 'newrequirement_model' );
		$date=date ( "Y-m-d", strtotime($date));
		$orders = $this->order_model->find_export_orders ($date);
		$totalproducts = $this->cost_model->get_products_by_date ('2015-08-11',$date);
		$costproducts = $this->orderdetail_model->get_orderdetails_by_date ('2015-08-11',$date);
		$lostproducts = $this->lost_model->get_products_by_date ('2015-08-11',$date);
		foreach($costproducts as $product){//计算库存
			foreach($totalproducts as  $key=>$totalproduct){
				if($product['productid']==$totalproduct['productid']){
					$totalproducts[$key]['amount']=$totalproduct['amount']-$product['amount'];
					break;
				}
			}
		}
		foreach($lostproducts as $product){//减去损耗的商品
			foreach($totalproducts as  $key=>$totalproduct){
				if($product['productid']==$totalproduct['productid']){
					$totalproducts[$key]['amount']=$totalproduct['amount']-$product['amount'];
					break;
				}
			}
		}
		$i = 3;
		if(!empty($orders)){
			$orderdetails = $this->orderdetail_model->find_export_orderdetails ($date);
			$products = array();
			foreach($orderdetails as $item){
				if(array_key_exists($item['id'],$products) ){
					$products[$item['id']]['amount']=$products[$item['id']]['amount']+$item['amount'];
					$products[$item['id']]['add']=$products[$item['id']]['add'].'+'.$item['amount'];
				}else{
					$name=$item ['name'];
					if($item ['type']==1){
						$name=$item ['name'].'(食堂专用)';
					}
					$product=array (
					'id' => $item ['id'],
					'name' => $name,
					'amount'=> $item['amount'],
					'unit'=> $item['unit'],
					'description'=> $item['description'],
					'add'=>$item['amount'],
					'stock'=>0
					);
					foreach($totalproducts as $tempproduct){
						if($item['id']==$tempproduct['productid']){
							$product=array (
							'id' => $item ['id'],
							'name' => $name,
							'amount'=> $item['amount'],
							'unit'=> $item['unit'],
							'description'=> $item['description'],
							'add'=>$item['amount'],
							'stock'=>$tempproduct['amount']
							);
							break;
						}
					}
					$products[$item['id']] =$product;
				}
			}
			foreach ( $products as $product ) {
				$objActSheet->getRowDimension($i)->setRowHeight(25);
				if(strstr($product ['add'],'+')){
					$objActSheet->setCellValue ( 'A' . $i, $product ['name'].'【'.$product ['add'].'】');
				}else{
					$objActSheet->setCellValue ( 'A' . $i, $product ['name']);
				}
				//$objActSheet->setCellValue ( 'A' . $i, $product ['name']);
				$objActSheet->mergeCells('A'.$i.':C'.$i);
				$objActSheet->setCellValue ( 'D' . $i, $product ['amount'] );
				$objActSheet->setCellValue ( 'E' . $i, $product ['unit'] );
				$length = strlen($product ['description']);
				if($length > 33){//超过33截断
					$product ['description']=substr($product ['description'],0,33);
				}
				$objActSheet->setCellValue ( 'F' . $i, $product ['description'] );
				if($product ['stock']<0){
					$objActSheet->setCellValue ( 'G' . $i, '无' );
				}elseif($product ['stock']>0&&$product ['stock']<$product ['amount'] ){
					$objActSheet->setCellValue ( 'G' . $i, $product ['stock'].'少' );
				}else{
					$objActSheet->setCellValue ( 'G' . $i, $product ['stock'] );
				}
				$i ++;
			}
			$styleArray = array(//加入边框
					'borders' => array(
							'allborders' => array(
									'style' => PHPExcel_Style_Border::BORDER_THIN
							),
					),
			);
			$objActSheet->getStyle('A2:G'.($i-1))->applyFromArray($styleArray);
			$i++;
			$j=$i;
			$objActSheet->setCellValue ( 'A'.$i, '饭店名称');
			$objActSheet->setCellValue ( 'B'.$i, '备注');
			$objActSheet->mergeCells('B'.$i.':G'.$i);
			$i++;
			foreach ( $orders as $order ) {
				if(!empty($order ['note'])&&trim($order ['note'])!=''){
					$objActSheet->setCellValue ( 'A' . $i, $order ['shopname'] );
					$objActSheet->setCellValue ( 'B' . $i, $order ['note'] );
					$objActSheet->mergeCells('B'.$i.':G'.$i);
					$length=87;
					$width=ceil(strlen($order ['note'])/$length);
					$objActSheet ->getStyle('B'.$i)->getAlignment()->setWrapText(true);//自动换行 
					$objActSheet->getRowDimension($i)->setRowHeight(15*$width);
					$objActSheet->setCellValue ( 'B' . $i, $order ['note']);
					$i ++;
				}
			}
			$objActSheet->getStyle('A'.$j.':G'.($i-1))->applyFromArray($styleArray);
			$i++;
			$k=$i;
			$objActSheet->setCellValue ( 'A'.$i, '商品名称');
			$objActSheet->mergeCells('A'.$i.':B'.$i);
			$objActSheet->setCellValue ( 'C'.$i, '饭店名称');
			$objActSheet->mergeCells('C'.$i.':D'.$i);
			$objActSheet->setCellValue ( 'E'.$i, '备注');
			$objActSheet->mergeCells('E'.$i.':G'.$i);
			$i++;
			foreach ( $products as $product ) {
				$requirements = $this->newrequirement_model->find_by_product_date ($product['id'],$date);
				//var_dump($requirements);
				if(!empty($requirements)){
					$objActSheet->setCellValue ( 'A'.$i, $product['name']);
					$objActSheet->mergeCells('A'.$i.':B'.$i);
					$length=41;
					foreach($requirements as $requirement){
						$objActSheet->setCellValue ( 'C'.$i, $requirement['name']);
						$objActSheet->mergeCells('C'.$i.':D'.$i);
						$objActSheet->mergeCells('E'.$i.':G'.$i);
						$width=ceil(strlen($requirement['content'])/$length);
						$objActSheet ->getStyle('E'.$i)->getAlignment()->setWrapText(true);//自动换行 
						$objActSheet->getRowDimension($i)->setRowHeight(15*$width);
						$objActSheet->setCellValue ( 'E' . $i, $requirement['content']);
						$i++;
					}
				}
			}
			//die();
			$objActSheet->getStyle('A'.$k.':G'.($i-1))->applyFromArray($styleArray);
			
			$objActSheet->getStyle ( 'A1:G' . $i)->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_LEFT );//左对齐
			$objActSheet->getStyle ( 'A1:G' .$i )->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);//垂直居中
		}
		// 设置列宽
		$objActSheet->getColumnDimension ( 'A' )->setWidth ( 20 );
		$objActSheet->getColumnDimension ( 'B' )->setWidth ( 20 );
		$objActSheet->getColumnDimension ( 'C' )->setWidth ( 10 );
		$objActSheet->getColumnDimension ( 'D' )->setWidth ( 5);
		$objActSheet->getColumnDimension ( 'E' )->setWidth ( 5 );
		$objActSheet->getColumnDimension ( 'F' )->setWidth ( 20);
		$objActSheet->getColumnDimension ( 'G' )->setWidth ( 5 );
		
		$objActSheet->getHeaderFooter()->setOddFooter('&B&C第&P页,共&N页');
		
		$outputFileName = '采购单.xls';
		$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
		// ob_start(); ob_flush();
		header ( "Content-Type: application/force-download" );
		header ( "Content-Type: application/octet-stream" );
		header ( "Content-Type: application/download" );
		header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
		header ( "Content-Transfer-Encoding: binary" );
		header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
		header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
		header ( "Pragma: no-cache" );
		$xlsWriter->save ( "php://output" );
	}
	/*
	 * 根据日期导出报价单
	 */
	public function exportQuotation() {
		$date = $this->uri->segment(4);
		$resultPHPExcel = new PHPExcel ();
		$objActSheet = $resultPHPExcel->getActiveSheet();
		$objActSheet->setCellValue ( 'A1', '采购日期：'.date ( "Y-m-d", strtotime ( "$date +1 day" )));
		$objActSheet->setCellValue ( 'A2', '商品名称' );
		$objActSheet->mergeCells('A2:C2');
		$objActSheet->setCellValue ( 'D2', '数量' );
		$objActSheet->setCellValue ( 'E2', '单位' );
		$objActSheet->setCellValue ( 'F2', '销售价' );
		$this->load->model ( 'order_model' );
		$this->load->model ( 'orderdetail_model' );
		$date=date ( "Y-m-d", strtotime($date));
		$orders = $this->order_model->find_export_orders ($date);
		$i = 3;
		if(!empty($orders)){
			$orderdetails = $this->orderdetail_model->find_export_orderdetails ($date);
			$products = array();
			foreach($orderdetails as $item){
				if(array_key_exists($item['id'],$products) ){
					$products[$item['id']]['amount']=$products[$item['id']]['amount']+$item['amount'];
					$products[$item['id']]['add']=$products[$item['id']]['add'].'+'.$item['amount'];
				}else{
					$product=array (
					'name' => $item ['name'],
					'amount'=> $item['amount'],
					'unit'=> $item['unit'],
					'price'=> $item['price'],
					'description'=> $item['description'],
					'add'=>$item['amount']
					);
					$products[$item['id']] =$product;
				}
			}
			foreach ( $products as $product ) {
				$objActSheet->getRowDimension($i)->setRowHeight(25);
				if(strstr($product ['add'],'+')){
					$objActSheet->setCellValue ( 'A' . $i, $product ['name'].'【'.$product ['add'].'】');
				}else{
					$objActSheet->setCellValue ( 'A' . $i, $product ['name']);
				}
				//$objActSheet->setCellValue ( 'A' . $i, $product ['name']);
				$objActSheet->mergeCells('A'.$i.':C'.$i);
				$objActSheet->setCellValue ( 'D' . $i, $product ['amount'] );
				$objActSheet->setCellValue ( 'E' . $i, $product ['unit'] );
				$objActSheet->setCellValue ( 'F' . $i, $product ['price'] .'元/'.$product ['unit'] );
				$i ++;
			}
			$styleArray = array(//加入边框
					'borders' => array(
							'allborders' => array(
									'style' => PHPExcel_Style_Border::BORDER_THIN
							),
					),
			);
			$objActSheet->getStyle('A2:F'.($i-1))->applyFromArray($styleArray);
			
			$objActSheet->setCellValue ( 'A'.($i + 1), '订单号');
			$objActSheet->setCellValue ( 'B'.($i + 1), '备注');
			$objActSheet->mergeCells('B'.($i + 1).':F'.($i + 1));
			$j=1;
			foreach ( $orders as $order ) {
				if(!empty($order ['note'])&&trim($order ['note'])!=''){
					$objActSheet->setCellValueExplicit( 'A' . ($i + 1+$j),$order ['orderno'],PHPExcel_Cell_DataType::TYPE_STRING);//暂时不管
					$objActSheet->getStyle('A' . ($i + 1+$j))->getNumberFormat()->setFormatCode("@");
					$objActSheet->setCellValue ( 'B' . ($i + 1+$j), $order ['note'] );
					$objActSheet->mergeCells('B'.($i + 1+$j).':F'.($i +1+$j));
					$length=87;
					$width=ceil(strlen($order ['note'])/$length);
					$objActSheet ->getStyle('B'.($i + 1+$j))->getAlignment()->setWrapText(true);//自动换行 
					$objActSheet->getRowDimension($i + 1+$j)->setRowHeight(15*$width);
					$objActSheet->setCellValue ( 'B' . ($i + 1+$j), '备注：'.$order ['note']);
					$j ++;
				}
			}
			$objActSheet->getStyle('A'.($i+1).':F'.($i +$j))->applyFromArray($styleArray);
			//左对齐
			$objActSheet->getStyle ( 'A1:F' . ($i +$j) )->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_LEFT );
			//垂直居中
			$objActSheet->getStyle ( 'A1:F' .($i +$j) )->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
		}
		// 设置列宽
		$objActSheet->getColumnDimension ( 'A' )->setWidth ( 20 );
		$objActSheet->getColumnDimension ( 'B' )->setWidth ( 20 );
		$objActSheet->getColumnDimension ( 'C' )->setWidth ( 10 );
		$objActSheet->getColumnDimension ( 'D' )->setWidth (5);
		$objActSheet->getColumnDimension ( 'E' )->setWidth ( 5 );
		$objActSheet->getColumnDimension ( 'F' )->setWidth ( 25);
		$outputFileName = '报价单.xls';
		$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
		// ob_start(); ob_flush();
		header ( "Content-Type: application/force-download" );
		header ( "Content-Type: application/octet-stream" );
		header ( "Content-Type: application/download" );
		header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
		header ( "Content-Transfer-Encoding: binary" );
		header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
		header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
		header ( "Pragma: no-cache" );
		$xlsWriter->save ( "php://output" );
	}
	/*
	 * 根据日期和付款方式导出日报单
	 */
	public function exportReport() {
		$date = $this->uri->segment(4);
		$payment = $this->uri->segment(6);
		$resultPHPExcel = new PHPExcel ();
		$objActSheet = $resultPHPExcel->getActiveSheet();
		$objActSheet->mergeCells('A1:H1');
		if($payment=="1"){
			$objActSheet->setCellValue ( 'A1', '集市宝线上销售日报单');
			$outputFileName = '线上日报单.xls';
		}
		if($payment=="2"){
			$objActSheet->setCellValue ( 'A1', '集市宝线下销售日报单');
			$outputFileName = '线下日报单.xls';
		}
		if($payment=="0"){
			$objActSheet->setCellValue ( 'A1', '集市宝总销售日报单');
			$outputFileName = '总日报单.xls';
		}
		$objActSheet->getStyle('A1')->getFont()->setBold(true);
		$objActSheet->getStyle('A1')->getFont()->setSize(25);
		$objActSheet->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objActSheet->setCellValue ( 'A3', '日期：'.date ( "Y年m月d日", strtotime ( "$date +1 day" )));
		$objActSheet->setCellValue ( 'G3', '单位：元');
		$objActSheet->setCellValue ( 'A4', '商品名称' );
		$objActSheet->mergeCells('A4:B4');
		$objActSheet->setCellValue ( 'C4', '单位' );
		$objActSheet->setCellValue ( 'D4', '数量' );
		$objActSheet->setCellValue ( 'E4', '单价' );
		$objActSheet->setCellValue ( 'F4', '金额' );
		$objActSheet->setCellValue ( 'G4', '成本' );
		$objActSheet->setCellValue ( 'H4', '毛利' );
		$this->load->model ( 'order_model' );
		$this->load->model ( 'orderdetail_model' );
		$date=date ( "Y-m-d", strtotime($date));
		$orders = $this->order_model->find_export_report ($date,$payment);
		$i = 5;
		if(!empty($orders)){
			$products = $this->orderdetail_model->find_export_report ($date,$payment);
			$alltotal=0;
			$allcost=0;
			$allprofit=0;
			foreach ( $products as $product ) {
				$objActSheet->getRowDimension($i)->setRowHeight(25);
				$objActSheet->setCellValue ( 'A' . $i, $product ['name']);
				$objActSheet->mergeCells('A'.$i.':B'.$i);
				$objActSheet->setCellValue ( 'C' . $i, $product ['unit'] );
				$objActSheet->setCellValue ( 'D' . $i, $product ['amount'] );
				$objActSheet->setCellValue ( 'E' . $i, $product ['price'] );
				$total=round($product ['price']*$product ['amount'] ,2);
				$cost=round($product ['purprice']*$product ['amount'] ,2);
				$profit=$total-$cost;
				$objActSheet->getStyle('E'.$i)->getNumberFormat()->setFormatCode('0.00');
				$objActSheet->getStyle('F'.$i)->getNumberFormat()->setFormatCode('0.00');
				$objActSheet->getStyle('G'.$i)->getNumberFormat()->setFormatCode('0.00');
				$objActSheet->getStyle('H'.$i)->getNumberFormat()->setFormatCode('0.00');
				$objActSheet->setCellValue ( 'F' . $i, $total);
				$objActSheet->setCellValue ( 'G' . $i, $cost);
				$objActSheet->setCellValue ( 'H' . $i, $profit);
				$alltotal+=$total;
				$allcost+=$cost;
				$allprofit+=$profit;
				$i ++;
			}
			$objActSheet->setCellValue ( 'A' . $i, '合计：');
			$objActSheet->mergeCells('A'.$i.':B'.$i);
			$objActSheet->getStyle('F'.$i)->getNumberFormat()->setFormatCode('0.00');
			$objActSheet->getStyle('G'.$i)->getNumberFormat()->setFormatCode('0.00');
			$objActSheet->getStyle('H'.$i)->getNumberFormat()->setFormatCode('0.00');
			$objActSheet->setCellValue ( 'F' . $i, $alltotal);
			$objActSheet->setCellValue ( 'G' . $i, $allcost);
			$objActSheet->setCellValue ( 'H' . $i, $allprofit);
			$styleArray = array(//加入边框
					'borders' => array(
							'allborders' => array(
									'style' => PHPExcel_Style_Border::BORDER_THIN
							),
					),
			);
			$objActSheet->getStyle('A4:H'.$i)->applyFromArray($styleArray);
			$i +=2;
			$objActSheet->setCellValue ( 'A' . $i, '复核：');
			$objActSheet->setCellValue ( 'E' . $i, '制单人：');
			//左对齐
			$objActSheet->getStyle ( 'A3:H' . $i)->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_LEFT );
			//垂直居中
			$objActSheet->getStyle ( 'A1:H' .$i)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
		}
		// 设置列宽
		$objActSheet->getColumnDimension ( 'A' )->setWidth ( 20 );
		$objActSheet->getColumnDimension ( 'B' )->setWidth ( 14 );
		$objActSheet->getColumnDimension ( 'C' )->setWidth (5);
		$objActSheet->getColumnDimension ( 'D' )->setWidth (5);
		$objActSheet->getColumnDimension ( 'E' )->setWidth (11);
		$objActSheet->getColumnDimension ( 'F' )->setWidth (11);
		$objActSheet->getColumnDimension ( 'G' )->setWidth (11);
		$objActSheet->getColumnDimension ( 'H' )->setWidth (11);
		
		if($payment=="0"){//全部日报单时
			$resultPHPExcel->createSheet();
			$resultPHPExcel->setactivesheetindex(1);
			$objActSheet = $resultPHPExcel->getActiveSheet();
			$objActSheet->setCellValue ( 'A1', '商品名称' );
			$objActSheet->mergeCells('A1:B1');
			$objActSheet->setCellValue ( 'C1', '单位' );
			$objActSheet->setCellValue ( 'D1', '数量' );
			$objActSheet->setCellValue ( 'E1', '销售价' );
			$objActSheet->setCellValue ( 'F1', '进货价' );
			$objActSheet->setCellValue ( 'G1', '金额' );
			$objActSheet->setCellValue ( 'H1', '成本' );
			$objActSheet->setCellValue ( 'I1', '毛利' );
			$i=2;
			$k=1;
			$cat=array("13","14","17","0");
			for($j=0;$j<4;$j++){
			$orderdetails = $this->orderdetail_model->find_export_reports ($date,$cat[$j]);
			$products = array();
			foreach($orderdetails as $item){
				if(array_key_exists($item['id'],$products) ){
					$products[$item['id']]['amount']=$products[$item['id']]['amount']+$item['amount'];
				}else{
					$product=array (
					'name' => $item ['name'],
					'amount'=> $item['amount'],
					'unit'=> $item['unit'],
					'price'=> $item['price'],
					'purprice'=>$item['purprice']
					);
					$products[$item['id']] =$product;
				}
			}
			$alltotal=0;
			$allcost=0;
			$allprofit=0;
			foreach ( $products as $product ) {
				$objActSheet->getRowDimension($i)->setRowHeight(25);
				$objActSheet->setCellValue ( 'A' . $i, $product ['name']);
				$objActSheet->mergeCells('A'.$i.':B'.$i);
				$objActSheet->setCellValue ( 'C' . $i, $product ['unit'] );
				$objActSheet->setCellValue ( 'D' . $i, $product ['amount'] );
				$objActSheet->setCellValue ( 'E' . $i, $product ['price'] );
				$objActSheet->setCellValue ( 'F' . $i, $product ['purprice'] );
				$total=round($product ['price']*$product ['amount'] ,2);
				$cost=round($product ['purprice']*$product ['amount'] ,2);
				$profit=$total-$cost;
				$objActSheet->getStyle('E'.$i)->getNumberFormat()->setFormatCode('0.00');
				$objActSheet->getStyle('F'.$i)->getNumberFormat()->setFormatCode('0.00');
				$objActSheet->getStyle('G'.$i)->getNumberFormat()->setFormatCode('0.00');
				$objActSheet->getStyle('H'.$i)->getNumberFormat()->setFormatCode('0.00');
				$objActSheet->getStyle('I'.$i)->getNumberFormat()->setFormatCode('0.00');
				$objActSheet->setCellValue ( 'G' . $i, $total);
				$objActSheet->setCellValue ( 'H' . $i, $cost);
				$objActSheet->setCellValue ( 'I' . $i, $profit);
				$alltotal+=$total;
				$allcost+=$cost;
				$allprofit+=$profit;
				$i ++;
			}
			$objActSheet->setCellValue ( 'A' . $i, '合计：');
			$objActSheet->mergeCells('A'.$i.':B'.$i);
			$objActSheet->getStyle('G'.$i)->getNumberFormat()->setFormatCode('0.00');
			$objActSheet->getStyle('H'.$i)->getNumberFormat()->setFormatCode('0.00');
			$objActSheet->getStyle('I'.$i)->getNumberFormat()->setFormatCode('0.00');
			$objActSheet->setCellValue ( 'G' . $i, $alltotal);
			$objActSheet->setCellValue ( 'H' . $i, $allcost);
			$objActSheet->setCellValue ( 'I' . $i, $allprofit);
			$styleArray = array(//加入边框
					'borders' => array(
							'allborders' => array(
									'style' => PHPExcel_Style_Border::BORDER_THIN
							),
					),
			);
			$objActSheet->getStyle('A'.$k.':I'.$i)->applyFromArray($styleArray);
			$i +=2;
			$k=$i;
			}
			//左对齐
			$objActSheet->getStyle ( 'A1:I' . $i)->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_LEFT );
			//垂直居中
			$objActSheet->getStyle ( 'A1:I' .$i)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
			
			$objActSheet->getColumnDimension ( 'A' )->setWidth ( 8.5 );
			$objActSheet->getColumnDimension ( 'B' )->setWidth ( 15.3);
			$objActSheet->getColumnDimension ( 'C' )->setWidth (5);
			$objActSheet->getColumnDimension ( 'D' )->setWidth (5);
			$objActSheet->getColumnDimension ( 'E' )->setWidth (10);
			$objActSheet->getColumnDimension ( 'F' )->setWidth (10);
			$objActSheet->getColumnDimension ( 'G' )->setWidth (10);
			$objActSheet->getColumnDimension ( 'H' )->setWidth (10);
			$objActSheet->getColumnDimension ( 'I' )->setWidth (10);
		}
		$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
		// ob_start(); ob_flush();
		header ( "Content-Type: application/force-download" );
		header ( "Content-Type: application/octet-stream" );
		header ( "Content-Type: application/download" );
		header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
		header ( "Content-Transfer-Encoding: binary" );
		header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
		header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
		header ( "Pragma: no-cache" );
		$xlsWriter->save ( "php://output" );
	}
	/*
	 * 根据起始日期得到要采购的商品列表(用于导出采购统计)
	 */
	public function exportOrderdetail() {
		$startdate = $this->uri->segment(4);
		$enddate = $this->uri->segment(6);
		$resultPHPExcel = new PHPExcel ();
		$objActSheet = $resultPHPExcel->getActiveSheet();
		$objActSheet->setCellValue ( 'A1', '日期：'.date ( "Y-m-d", strtotime ($startdate)).'至'.date ( "Y-m-d", strtotime ($enddate)));
		$objActSheet->setCellValue ( 'A2', '商品名称' );
		$objActSheet->mergeCells('A2:C2');
		$objActSheet->setCellValue ( 'D2', '数量' );
		$objActSheet->setCellValue ( 'E2', '单位' );
		$objActSheet->setCellValue ( 'F2', '简单描述' );
		$this->load->model ( 'order_model' );
		$this->load->model ( 'orderdetail_model' );
		$startdate=date ( "Y-m-d", strtotime($startdate));
		$enddate=date ( "Y-m-d", strtotime($enddate));
		$orders = $this->order_model->find_export_order ($startdate,$enddate);
		$i = 3;
		if(!empty($orders)){
			$products = $this->orderdetail_model->find_export_orderdetail ($startdate,$enddate);
			foreach ( $products as $product ) {
				$objActSheet->getRowDimension($i)->setRowHeight(25);
				$objActSheet->setCellValue ( 'A' . $i, $product ['name']);
				$objActSheet->mergeCells('A'.$i.':C'.$i);
				$objActSheet->setCellValue ( 'D' . $i, $product ['amount'] );
				$objActSheet->setCellValue ( 'E' . $i, $product ['unit'] );
				$length = strlen($product ['description']);
				if($length > 33){//超过33截断
					$product ['description']=substr($product ['description'],0,33);
				}
				$objActSheet->setCellValue ( 'F' . $i, $product ['description'] );
				$i ++;
			}
			$styleArray = array(//加入边框
					'borders' => array(
							'allborders' => array(
									'style' => PHPExcel_Style_Border::BORDER_THIN
							),
					),
			);
			$objActSheet->getStyle('A2:F'.($i-1))->applyFromArray($styleArray);
		
			//左对齐
			$objActSheet->getStyle ( 'A1:F' . $i)->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_LEFT );
			//垂直居中
			$objActSheet->getStyle ( 'A1:F' .$i)->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
		}
		// 设置列宽
		$objActSheet->getColumnDimension ( 'A' )->setWidth ( 20 );
		$objActSheet->getColumnDimension ( 'B' )->setWidth ( 20 );
		$objActSheet->getColumnDimension ( 'C' )->setWidth ( 10 );
		$objActSheet->getColumnDimension ( 'D' )->setWidth (5);
		$objActSheet->getColumnDimension ( 'E' )->setWidth ( 5 );
		$objActSheet->getColumnDimension ( 'F' )->setWidth ( 25);
		$outputFileName = '采购统计.xls';
		$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
		// ob_start(); ob_flush();
		header ( "Content-Type: application/force-download" );
		header ( "Content-Type: application/octet-stream" );
		header ( "Content-Type: application/download" );
		header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
		header ( "Content-Transfer-Encoding: binary" );
		header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
		header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
		header ( "Pragma: no-cache" );
		$xlsWriter->save ( "php://output" );
	}
	/*
	 * 返回选择分拣表页面
	 */
	public function selectsort() {
		$date = $this->uri->segment ( 4 );
		$this->load->model ( 'order_model' );
		$date=date ( "Y-m-d", strtotime($date));
		$users = $this->order_model->find_order_users_by_date ($date);
		$regions = $this->order_model->find_order_district_by_date ($date);
		$data['date']=$date;
		$data['users']=$users;
		$data['regions']=$regions;
		$data ['title'] = '订单详情 - 集市宝仓库管理系统';
		$this->load->view ( 'header', $data );
		$this->load->view ( 'order/sort' );
		$this->load->view ( 'footer' );
	}
	/*
	 * 根据选择的商家导出分拣表
	 */
	public function exportNewsort() {
		$user=$this->input->post ( 'user' ) ;
		$date=$this->input->post ( 'date' ) ;
		$str =implode(',',$user);
		$resultPHPExcel = new PHPExcel ();
		$objActSheet = $resultPHPExcel->getActiveSheet();
			$styleArray = array(//加入边框
					'borders' => array(
							'allborders' => array(
									'style' => PHPExcel_Style_Border::BORDER_THIN
							),
					),
			);
		$objActSheet->setCellValue ( 'A1', '饭店编号');
		$objActSheet->setCellValue ( 'B1', '饭店名称' );
		$this->load->model ( 'order_model' );
		$this->load->model ( 'orderdetail_model' );
		$this->load->model ( 'requirement_model' );
		$date=date ( "Y-m-d", strtotime($date));
		$orders = $this->order_model->find_new_export_orders ($date,$str);
		$i = 2;
		$shops = array();
		if(!empty($orders)){
			foreach ( $orders as $order ) {
				$objActSheet->setCellValue ( 'A'.$i, '['.($i-1).']');
				$objActSheet->getStyle('A'.$i)->getFont()->setBold(true);
				$objActSheet->getStyle('A'.$i)->getFont()->setSize(16);
				$objActSheet->setCellValue ( 'B'.$i, $order['shopname']);
				$shops[$order['id']]=$i-1;
				$i++;
			}
			$objActSheet->getStyle('A1:B'.($i-1))->applyFromArray($styleArray);
			$i++;
			$j=$i;
			
			$objActSheet->setCellValue ( 'A' . $i, "饭店名称");
			$objActSheet->setCellValue ( 'B' . $i, "备注");
			$objActSheet->mergeCells('B'.$i.':E'.$i);
			$i++;
			foreach ( $orders as $order ) {
				if(!empty($order ['note'])&&trim($order ['note'])!=''){
					$objActSheet->setCellValue ( 'A' . $i, $order ['shopname'] );
					$objActSheet->setCellValue ( 'B' . $i, $order ['note'] );
					$objActSheet->mergeCells('B'.$i.':E'.$i);
					$length=79;
					$width=ceil(strlen($order ['note'])/$length);
					$objActSheet ->getStyle('B'.$i)->getAlignment()->setWrapText(true);//自动换行 
					$objActSheet->getRowDimension($i)->setRowHeight(15*$width);
					$i ++;
				}
			}
			$objActSheet->getStyle('A'.$j.':E'.($i-1))->applyFromArray($styleArray);
			$i++;
			
			$objActSheet->setCellValue ( 'A'.$i, '分拣方案');
			$orderdetails = $this->orderdetail_model->find_new_export_sort ($date,$str);
			$i++;
			$y=$i;
			$a=$i;
			$objActSheet->setCellValue ( 'A'.$i, $orderdetails[0]['name']);
			$i++;
			$total=0;
			$objActSheet->setCellValue ( 'A'.$i, '['.$shops[$orderdetails[0]['id']].']');
			$objActSheet->getStyle('A'.$i)->getFont()->setBold(true);
			$objActSheet->getStyle('A'.$i)->getFont()->setSize(16);
			$objActSheet->getStyle ('A'.$i)->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_RIGHT );
			$requirement = $this->requirement_model->find_by_user_and_product ($orderdetails[0]['userid'],$orderdetails[0]['productid']);
			if(!empty($requirement)){
				$name=$orderdetails[0]['shopname'].'【'.$requirement['content'].'】';
			}else{
				$name=$orderdetails[0]['shopname'];
			}
			$newlength=68;
			$width=ceil(strlen($name)/$newlength);
			$objActSheet->setCellValue ( 'B'.$i, $name);
			$objActSheet->mergeCells('B'.$i.':D'.$i);
			$objActSheet ->getStyle('B'.$i)->getAlignment()->setWrapText(true);//自动换行 
			$objActSheet->getRowDimension($i)->setRowHeight(21*$width);
			$objActSheet->setCellValue ( 'E'.$i, $orderdetails[0]['amount'].$orderdetails[0]['unit']);
			$objActSheet->getStyle('E'.$i)->getFont()->setBold(true);
			$objActSheet->getStyle('E'.$i)->getFont()->setSize(16);
			$total+=$orderdetails[0]['amount'];
			$size=count($orderdetails);
			for($j=1;$j<$size;$j++){
				if($orderdetails[$j]['productid']==$orderdetails[$j-1]['productid']){
					$i++;
					$objActSheet->setCellValue ( 'A'.$i, '['.$shops[$orderdetails[$j]['id']].']');
					$objActSheet->getStyle('A'.$i)->getFont()->setBold(true);
					$objActSheet->getStyle('A'.$i)->getFont()->setSize(16);
					$objActSheet->getStyle ('A'.$i)->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_RIGHT );
					$requirement = $this->requirement_model->find_by_user_and_product ($orderdetails[$j]['userid'],$orderdetails[$j]['productid']);
					if(!empty($requirement)){
						$name=$orderdetails[$j]['shopname'].'【'.$requirement['content'].'】';
					}else{
						$name=$orderdetails[$j]['shopname'];
					}
					$width=ceil(strlen($name)/$newlength);
					$objActSheet->setCellValue ( 'B'.$i, $name);
					$objActSheet->mergeCells('B'.$i.':D'.$i);
					$objActSheet ->getStyle('B'.$i)->getAlignment()->setWrapText(true);//自动换行 
					$objActSheet->getRowDimension($i)->setRowHeight(21*$width);
					$objActSheet->setCellValue ( 'E'.$i, $orderdetails[$j]['amount'].$orderdetails[$j]['unit']);
					$objActSheet->getStyle('E'.$i)->getFont()->setBold(true);
					$objActSheet->getStyle('E'.$i)->getFont()->setSize(16);
					$total+=$orderdetails[$j]['amount'];
				}else{
					$name=$orderdetails[$j-1]['name'];
					if($orderdetails[$j-1]['type']==1){
						$name=$orderdetails[$j-1]['name'].'(食堂专用)';
					}
					$objActSheet->setCellValue ( 'A'.$y, $name.'-'.$total.$orderdetails[$j-1]['unit']);
					$objActSheet->setCellValue ( 'B'.$y, $orderdetails[$j-1]['description']);
					$objActSheet->mergeCells('B'.$y.':E'.$y);
					//$objActSheet->getStyle('A'.$y.':C'.$i)->applyFromArray($styleArray);
					$i+=1;
					$y=$i;
					$objActSheet->setCellValue ( 'A'.$i, $orderdetails[$j]['name']);
					$i++;
					$total=0;
					$objActSheet->setCellValue ( 'A'.$i, '['.$shops[$orderdetails[$j]['id']].']');
					$objActSheet->getStyle('A'.$i)->getFont()->setBold(true);
					$objActSheet->getStyle('A'.$i)->getFont()->setSize(16);
					$objActSheet->getStyle ('A'.$i)->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_RIGHT );
					$requirement = $this->requirement_model->find_by_user_and_product ($orderdetails[$j]['userid'],$orderdetails[$j]['productid']);
					if(!empty($requirement)){
						$name=$orderdetails[$j]['shopname'].'【'.$requirement['content'].'】';
					}else{
						$name=$orderdetails[$j]['shopname'];
					}
					$width=ceil(strlen($name)/$newlength);
					$objActSheet->setCellValue ( 'B'.$i, $name);
					$objActSheet->mergeCells('B'.$i.':D'.$i);
					$objActSheet ->getStyle('B'.$i)->getAlignment()->setWrapText(true);//自动换行 
					$objActSheet->getRowDimension($i)->setRowHeight(21*$width);
					$objActSheet->setCellValue ( 'E'.$i, $orderdetails[$j]['amount'].$orderdetails[$j]['unit']);
					$objActSheet->getStyle('E'.$i)->getFont()->setBold(true);
					$objActSheet->getStyle('E'.$i)->getFont()->setSize(16);
					$total+=$orderdetails[$j]['amount'];
				}
				if($j==$size-1){
					$name=$orderdetails[$j]['name'];
					if($orderdetails[$j]['type']==1){
						$name=$orderdetails[$j]['name'].'(食堂专用)';
					}
					$objActSheet->setCellValue ( 'A'.$y, $name.'-'.$total.$orderdetails[$j]['unit']);
					$objActSheet->setCellValue ( 'B'.$y, $orderdetails[$j]['description']);
					$objActSheet->mergeCells('B'.$y.':E'.$y);
				}
			}	
			$objActSheet->getStyle('A'.$a.':E'.$i)->applyFromArray($styleArray);
		}
		// 设置列宽
		$objActSheet->getColumnDimension ( 'A' )->setWidth ( 30 );
		$objActSheet->getColumnDimension ( 'B' )->setWidth ( 30 );
		$objActSheet->getColumnDimension ( 'C' )->setWidth ( 10 );
		
		$objActSheet->getHeaderFooter()->setOddFooter('&B&C第&P页,共&N页');
		
		$outputFileName = '分拣表.xls';
		$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
		// ob_start(); ob_flush();
		header ( "Content-Type: application/force-download" );
		header ( "Content-Type: application/octet-stream" );
		header ( "Content-Type: application/download" );
		header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
		header ( "Content-Transfer-Encoding: binary" );
		header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
		header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
		header ( "Pragma: no-cache" );
		$xlsWriter->save ( "php://output" );
	}
	/*
	 * 根据日期得到商品分拣表(导出分拣表)
	 */
	public function exportSort() {
		$date = $this->uri->segment(4);
		$resultPHPExcel = new PHPExcel ();
		$objActSheet = $resultPHPExcel->getActiveSheet();
			$styleArray = array(//加入边框
					'borders' => array(
							'allborders' => array(
									'style' => PHPExcel_Style_Border::BORDER_THIN
							),
					),
			);
		$objActSheet->setCellValue ( 'A1', '饭店编号');
		$objActSheet->setCellValue ( 'B1', '饭店名称' );
		$this->load->model ( 'order_model' );
		$this->load->model ( 'orderdetail_model' );
		$this->load->model ( 'requirement_model' );
		$date=date ( "Y-m-d", strtotime($date));
		$orders = $this->order_model->find_export_orders ($date);
		$i = 2;
		$shops = array();
		if(!empty($orders)){
			foreach ( $orders as $order ) {
				$objActSheet->setCellValue ( 'A'.$i, '['.($i-1).']');
				$objActSheet->getStyle('A'.$i)->getFont()->setBold(true);
				$objActSheet->getStyle('A'.$i)->getFont()->setSize(16);
				$objActSheet->setCellValue ( 'B'.$i, $order['shopname']);
				$shops[$order['id']]=$i-1;
				$i++;
			}
			$objActSheet->getStyle('A1:B'.($i-1))->applyFromArray($styleArray);
			$i++;
			$j=$i;
			
			$objActSheet->setCellValue ( 'A' . $i, "饭店名称");
			$objActSheet->setCellValue ( 'B' . $i, "备注");
			$objActSheet->mergeCells('B'.$i.':E'.$i);
			$i++;
			foreach ( $orders as $order ) {
				if(!empty($order ['note'])&&trim($order ['note'])!=''){
					$objActSheet->setCellValue ( 'A' . $i, $order ['shopname'] );
					$objActSheet->setCellValue ( 'B' . $i, $order ['note'] );
					$objActSheet->mergeCells('B'.$i.':E'.$i);
					$length=79;
					$width=ceil(strlen($order ['note'])/$length);
					$objActSheet ->getStyle('B'.$i)->getAlignment()->setWrapText(true);//自动换行 
					$objActSheet->getRowDimension($i)->setRowHeight(15*$width);
					$i ++;
				}
			}
			$objActSheet->getStyle('A'.$j.':E'.($i-1))->applyFromArray($styleArray);
			$i++;
			
			$objActSheet->setCellValue ( 'A'.$i, '分拣方案');
			$orderdetails = $this->orderdetail_model->find_export_sort ($date);
			$i++;
			$y=$i;
			$a=$i;
			$objActSheet->setCellValue ( 'A'.$i, $orderdetails[0]['name']);
			$i++;
			$total=0;
			$objActSheet->setCellValue ( 'A'.$i, '['.$shops[$orderdetails[0]['id']].']');
			$objActSheet->getStyle('A'.$i)->getFont()->setBold(true);
			$objActSheet->getStyle('A'.$i)->getFont()->setSize(16);
			$objActSheet->getStyle ('A'.$i)->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_RIGHT );
			$requirement = $this->requirement_model->find_by_user_and_product ($orderdetails[0]['userid'],$orderdetails[0]['productid']);
			if(!empty($requirement)){
				$name=$orderdetails[0]['shopname'].'【'.$requirement['content'].'】';
			}else{
				$name=$orderdetails[0]['shopname'];
			}
			$newlength=68;
			$width=ceil(strlen($name)/$newlength);
			$objActSheet->setCellValue ( 'B'.$i, $name);
			$objActSheet->mergeCells('B'.$i.':D'.$i);
			$objActSheet ->getStyle('B'.$i)->getAlignment()->setWrapText(true);//自动换行 
			$objActSheet->getRowDimension($i)->setRowHeight(21*$width);
			$objActSheet->setCellValue ( 'E'.$i, $orderdetails[0]['amount'].$orderdetails[0]['unit']);
			$objActSheet->getStyle('E'.$i)->getFont()->setBold(true);
			$objActSheet->getStyle('E'.$i)->getFont()->setSize(16);
			$total+=$orderdetails[0]['amount'];
			$size=count($orderdetails);
			for($j=1;$j<$size;$j++){
				if($orderdetails[$j]['productid']==$orderdetails[$j-1]['productid']){
					$i++;
					$objActSheet->setCellValue ( 'A'.$i, '['.$shops[$orderdetails[$j]['id']].']');
					$objActSheet->getStyle('A'.$i)->getFont()->setBold(true);
					$objActSheet->getStyle('A'.$i)->getFont()->setSize(16);
					$objActSheet->getStyle ('A'.$i)->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_RIGHT );
					$requirement = $this->requirement_model->find_by_user_and_product ($orderdetails[$j]['userid'],$orderdetails[$j]['productid']);
					if(!empty($requirement)){
						$name=$orderdetails[$j]['shopname'].'【'.$requirement['content'].'】';
					}else{
						$name=$orderdetails[$j]['shopname'];
					}
					$width=ceil(strlen($name)/$newlength);
					$objActSheet->setCellValue ( 'B'.$i, $name);
					$objActSheet->mergeCells('B'.$i.':D'.$i);
					$objActSheet ->getStyle('B'.$i)->getAlignment()->setWrapText(true);//自动换行 
					$objActSheet->getRowDimension($i)->setRowHeight(21*$width);
					$objActSheet->setCellValue ( 'E'.$i, $orderdetails[$j]['amount'].$orderdetails[$j]['unit']);
					$objActSheet->getStyle('E'.$i)->getFont()->setBold(true);
					$objActSheet->getStyle('E'.$i)->getFont()->setSize(16);
					$total+=$orderdetails[$j]['amount'];
				}else{
					$name=$orderdetails[$j-1]['name'];
					if($orderdetails[$j-1]['type']==1){
						$name=$orderdetails[$j-1]['name'].'(食堂专用)';
					}
					$objActSheet->setCellValue ( 'A'.$y, $name.'-'.$total.$orderdetails[$j-1]['unit']);
					$objActSheet->setCellValue ( 'B'.$y, $orderdetails[$j-1]['description']);
					$objActSheet->mergeCells('B'.$y.':E'.$y);
					//$objActSheet->getStyle('A'.$y.':C'.$i)->applyFromArray($styleArray);
					$i+=1;
					$y=$i;
					$objActSheet->setCellValue ( 'A'.$i, $orderdetails[$j]['name']);
					$i++;
					$total=0;
					$objActSheet->setCellValue ( 'A'.$i, '['.$shops[$orderdetails[$j]['id']].']');
					$objActSheet->getStyle('A'.$i)->getFont()->setBold(true);
					$objActSheet->getStyle('A'.$i)->getFont()->setSize(16);
					$objActSheet->getStyle ('A'.$i)->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_RIGHT );
					$requirement = $this->requirement_model->find_by_user_and_product ($orderdetails[$j]['userid'],$orderdetails[$j]['productid']);
					if(!empty($requirement)){
						$name=$orderdetails[$j]['shopname'].'【'.$requirement['content'].'】';
					}else{
						$name=$orderdetails[$j]['shopname'];
					}
					$width=ceil(strlen($name)/$newlength);
					$objActSheet->setCellValue ( 'B'.$i, $name);
					$objActSheet->mergeCells('B'.$i.':D'.$i);
					$objActSheet ->getStyle('B'.$i)->getAlignment()->setWrapText(true);//自动换行 
					$objActSheet->getRowDimension($i)->setRowHeight(21*$width);
					$objActSheet->setCellValue ( 'E'.$i, $orderdetails[$j]['amount'].$orderdetails[$j]['unit']);
					$objActSheet->getStyle('E'.$i)->getFont()->setBold(true);
					$objActSheet->getStyle('E'.$i)->getFont()->setSize(16);
					$total+=$orderdetails[$j]['amount'];
				}
				if($j==$size-1){
					$name=$orderdetails[$j]['name'];
					if($orderdetails[$j]['type']==1){
						$name=$orderdetails[$j]['name'].'(食堂专用)';
					}
					$objActSheet->setCellValue ( 'A'.$y, $name.'-'.$total.$orderdetails[$j]['unit']);
					$objActSheet->setCellValue ( 'B'.$y, $orderdetails[$j]['description']);
					$objActSheet->mergeCells('B'.$y.':E'.$y);
				}
			}	
			$objActSheet->getStyle('A'.$a.':E'.$i)->applyFromArray($styleArray);
		}
		// 设置列宽
		$objActSheet->getColumnDimension ( 'A' )->setWidth ( 30 );
		$objActSheet->getColumnDimension ( 'B' )->setWidth ( 30 );
		$objActSheet->getColumnDimension ( 'C' )->setWidth ( 10 );
		
		$objActSheet->getHeaderFooter()->setOddFooter('&B&C第&P页,共&N页');
		
		$outputFileName = '分拣表.xls';
		$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
		// ob_start(); ob_flush();
		header ( "Content-Type: application/force-download" );
		header ( "Content-Type: application/octet-stream" );
		header ( "Content-Type: application/download" );
		header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
		header ( "Content-Transfer-Encoding: binary" );
		header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
		header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
		header ( "Pragma: no-cache" );
		$xlsWriter->save ( "php://output" );
	}
	/*
	 * 根据日期得到要采购的供货商商品列表
	 */
	public function exportSupply() {
		$date = $this->uri->segment(4);
		$resultPHPExcel = new PHPExcel ();
		$objActSheet = $resultPHPExcel->getActiveSheet();
		$objActSheet->setCellValue ( 'A1', '采购日期：'.date ( "Y-m-d", strtotime ( "$date +1 day" )));
		$objActSheet->setCellValue ( 'A2', '商品名称' );
		$objActSheet->mergeCells('A2:C2');
		$objActSheet->setCellValue ( 'D2', '数量' );
		$objActSheet->setCellValue ( 'E2', '单位' );
		$objActSheet->setCellValue ( 'F2', '简单描述' );
		$this->load->model ( 'orderdetail_model' );
		$date=date ( "Y-m-d", strtotime($date));
		$products = $this->orderdetail_model->find_supply_orderdetails_by_date ($date);
		$i = 3;
		if(!empty($products)){
			foreach ( $products as $product ) {
				$objActSheet->getRowDimension($i)->setRowHeight(25);
				$objActSheet->setCellValue ( 'A' . $i, $product ['name']);
				$objActSheet->mergeCells('A'.$i.':C'.$i);
				$objActSheet->setCellValue ( 'D' . $i, $product ['amount'] );
				$objActSheet->setCellValue ( 'E' . $i, $product ['unit'] );
				$length = strlen($product ['description']);
				if($length > 33){//超过33截断
					$product ['description']=substr($product ['description'],0,33);
				}
				$objActSheet->setCellValue ( 'F' . $i, $product ['description'] );
				$i ++;
			}
			$styleArray = array(//加入边框
					'borders' => array(
							'allborders' => array(
									'style' => PHPExcel_Style_Border::BORDER_THIN
							),
					),
			);
			$objActSheet->getStyle('A2:F'.($i-1))->applyFromArray($styleArray);
			//左对齐
			$objActSheet->getStyle ( 'A1:F' .$i )->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_LEFT );
			//垂直居中
			$objActSheet->getStyle ( 'A1:F' .$i )->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
		}
		// 设置列宽
		$objActSheet->getColumnDimension ( 'A' )->setWidth ( 20 );
		$objActSheet->getColumnDimension ( 'B' )->setWidth ( 20 );
		$objActSheet->getColumnDimension ( 'C' )->setWidth ( 10 );
		$objActSheet->getColumnDimension ( 'D' )->setWidth (5);
		$objActSheet->getColumnDimension ( 'E' )->setWidth ( 5 );
		$objActSheet->getColumnDimension ( 'F' )->setWidth ( 25);
		$outputFileName = '供应商采购单.xls';
		$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
		// ob_start(); ob_flush();
		header ( "Content-Type: application/force-download" );
		header ( "Content-Type: application/octet-stream" );
		header ( "Content-Type: application/download" );
		header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
		header ( "Content-Transfer-Encoding: binary" );
		header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
		header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
		header ( "Pragma: no-cache" );
		$xlsWriter->save ( "php://output" );
	}
	/*
	 * 根据日期得到要采购的非供货商商品列表
	 */
	public function exportNosupply() {
		$date = $this->uri->segment(4);
		$resultPHPExcel = new PHPExcel ();
		$objActSheet = $resultPHPExcel->getActiveSheet();
		$objActSheet->setCellValue ( 'A1', '采购日期：'.date ( "Y-m-d", strtotime ( "$date +1 day" )));
		$objActSheet->setCellValue ( 'A2', '商品名称' );
		$objActSheet->mergeCells('A2:C2');
		$objActSheet->setCellValue ( 'D2', '数量' );
		$objActSheet->setCellValue ( 'E2', '单位' );
		$objActSheet->setCellValue ( 'F2', '简单描述' );
		$this->load->model ( 'order_model' );
		$this->load->model ( 'orderdetail_model' );
		$date=date ( "Y-m-d", strtotime($date));
		$orders = $this->order_model->find_export_orders ($date);
		$orderdetails = $this->orderdetail_model->find_nosupply_orderdetails_by_date ($date);
			$i = 3;
			$products = array();
			foreach($orderdetails as $item){
				if(array_key_exists($item['id'],$products) ){
					$products[$item['id']]['amount']=$products[$item['id']]['amount']+$item['amount'];
					$products[$item['id']]['add']=$products[$item['id']]['add'].'+'.$item['amount'];
				}else{
					$product=array (
					'name' => $item ['name'],
					'amount'=> $item['amount'],
					'unit'=> $item['unit'],
					'description'=> $item['description'],
					'add'=>$item['amount'],
					);
					$products[$item['id']] =$product;
				}
			}
			foreach ( $products as $product ) {
				$objActSheet->getRowDimension($i)->setRowHeight(25);
				if(strstr($product ['add'],'+')){
					$objActSheet->setCellValue ( 'A' . $i, $product ['name'].'【'.$product ['add'].'】');
				}else{
					$objActSheet->setCellValue ( 'A' . $i, $product ['name']);
				}
				$objActSheet->mergeCells('A'.$i.':C'.$i);
				$objActSheet->setCellValue ( 'D' . $i, $product ['amount'] );
				$objActSheet->setCellValue ( 'E' . $i, $product ['unit'] );
				$length = strlen($product ['description']);
				if($length > 33){//超过33截断
					$product ['description']=substr($product ['description'],0,33);
				}
				$objActSheet->setCellValue ( 'F' . $i, $product ['description'] );
				$i ++;
			}
			$styleArray = array(//加入边框
					'borders' => array(
							'allborders' => array(
									'style' => PHPExcel_Style_Border::BORDER_THIN
							),
					),
			);
			$objActSheet->getStyle('A2:F'.($i-1))->applyFromArray($styleArray);
			
			$objActSheet->setCellValue ( 'A'.($i + 1), '订单号');
			$objActSheet->setCellValue ( 'B'.($i + 1), '备注');
			$objActSheet->mergeCells('B'.($i + 1).':F'.($i + 1));
			$j=1;
			foreach ( $orders as $order ) {
				if(!empty($order ['note'])&&trim($order ['note'])!=''){
					$objActSheet->setCellValueExplicit( 'A' . ($i + 1+$j),$order ['orderno'],PHPExcel_Cell_DataType::TYPE_STRING);//暂时不管
					$objActSheet->getStyle('A' . ($i + 1+$j))->getNumberFormat()->setFormatCode("@");
					$objActSheet->setCellValue ( 'B' . ($i + 1+$j), $order ['note'] );
					$objActSheet->mergeCells('B'.($i + 1+$j).':F'.($i +1+$j));
					$length=87;
					$width=ceil(strlen($order ['note'])/$length);
					$objActSheet ->getStyle('B'.($i + 1+$j))->getAlignment()->setWrapText(true);//自动换行 
					$objActSheet->getRowDimension($i + 1+$j)->setRowHeight(15*$width);
					$objActSheet->setCellValue ( 'B' . ($i + 1+$j), '备注：'.$order ['note']);
					$j ++;
				}
			}
			$objActSheet->getStyle('A'.($i+1).':F'.($i +$j))->applyFromArray($styleArray);
			$objActSheet->getStyle ( 'A1:F' . ($i +$j) )->getAlignment ()->setHorizontal ( PHPExcel_Style_Alignment::HORIZONTAL_LEFT );//左对齐
			$objActSheet->getStyle ( 'A1:F' .($i +$j) )->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);//垂直居中
			
		// 设置列宽
		$objActSheet->getColumnDimension ( 'A' )->setWidth ( 20 );
		$objActSheet->getColumnDimension ( 'B' )->setWidth ( 20 );
		$objActSheet->getColumnDimension ( 'C' )->setWidth ( 10 );
		$objActSheet->getColumnDimension ( 'D' )->setWidth (5);
		$objActSheet->getColumnDimension ( 'E' )->setWidth ( 5 );
		$objActSheet->getColumnDimension ( 'F' )->setWidth ( 25);
		$outputFileName = '非供应商采购单.xls';
		$xlsWriter = new PHPExcel_Writer_Excel5 ( $resultPHPExcel );
		// ob_start(); ob_flush();
		header ( "Content-Type: application/force-download" );
		header ( "Content-Type: application/octet-stream" );
		header ( "Content-Type: application/download" );
		header ( 'Content-Disposition:inline;filename="' . $outputFileName . '"' );
		header ( "Content-Transfer-Encoding: binary" );
		header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
		header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
		header ( "Cache-Control: must-revalidate, post-check=0, pre-check=0" );
		header ( "Pragma: no-cache" );
		$xlsWriter->save ( "php://output" );
	}
	/*
	 * 记录库存修改
	 */
	private function record($orderid,$productid,$amount,$num,$type){
		$this->load->model ( 'stockrecord_model' );//库存记录
		$record = array (
			'orderid' => $orderid,
			'productid' => $productid,
			'amount' => $amount,
			'num' => $num,
			'type' => $type,
			'record_time' => date ( "Y-m-d H:i:s" )  
		);
		$this->stockrecord_model->create ( $record );
	}
	/*
	 * 拆分商品操作
	 */
	private function check_divide_product($productid){
		$this->load->model ( 'product_model' );
		$product=$this->product_model->load($productid);
		$this->load->model ( 'divide_model' );
		$this->load->model ( 'lost_model' );
		$this->load->model ( 'cost_model' );
		$divide=$this->divide_model->find_by_productid ( $productid );
		if($divide['stock']>0){//默认是库存管理
			if($divide['stock']-1>0){//库存小于等于0记为补货中
				$product1=array(
					'stock' => $divide['stock']-1
				);
			}else{
				$product1=array(
					'stock' => $divide['stock']-1,
					'short' => 1
				);
			}
			$this->product_model->update ( $divide['productid'],$product1);//箱类商品减1
			if($product['stock']+$divide['amount']>0){//大于0取消补货中
				$product2=array(
					'stock' => $product['stock']+$divide['amount'],
					'short' => 0
				);
			}else{
				$product2=array(
					'stock' => $product['stock']+$divide['amount']
				);
			}
			$this->product_model->update ( $productid,$product2);//单类商品加上对应数量
			$lost = array (
			    'productid' => $divide['productid'],
				'amount' => 1,
				'total' => 0,
				'type' => 3,
				'lost_time' => date ( "Y-m-d" ),
				'note' => "拆分"
			);
			$lostid=$this->lost_model->create ( $lost );
			$this->record($lostid,$divide['productid'],-1,$divide['stock']-1,9);
			$cost = array (
			    'productid' => $productid,
				'name' => $product['name'],
				'price' => 0, 
				'amount' => $divide['amount'],
				'unit' => $product['unit'], 
				'total' => 0,
				'cost_time' => date ( "Y-m-d" ),
				'note' => "拆分", 
			);
			$costid=$this->cost_model->create ( $cost );
			$this->record($costid,$productid,$divide['amount'],$product['stock']+$divide['amount'],9);
		}
	}
	/*
	 * 随机生成订单编号
	 */
	private function build_order_no() {//可以作为help类
		return date ( 'Ymd' ) . substr ( implode ( NULL, array_map ( 'ord', str_split ( substr ( uniqid (), 7, 13 ), 1 ) ) ), 0, 8 );
	}
}